package com.atguigu.lease.common.exception;

import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * projectName: com.atguigu.lease.common.exception
 *
 * @author: 顾司羽
 * time: 2024/12/10 14:19 周二
 * description: 全局异常处理 / 声明式异常处理
 *
 *        common中导入web-starter
 *        <dependency>
 *            <groupId>org.springframework.boot</groupId>
 *            <artifactId>spring-boot-starter-web</artifactId>
 *        </dependency>
 *
 *   定义一个全局异常处理类
 *   类上添加注解 @ControllerAdvice @RestControllerAdvice
 *   定义异常处理的方法,至少保证一个Exception兜底异常处理(Result.fail() 201)
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

/*    //在Result.java中 自定义的方法 ------------------------
    public static <T> Result<T> build(String message,int code) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMessage(message);
        return result;
        //-------------------------------------
    }*/
    @ExceptionHandler(LeaseStatusException.class)//检查是否存在签约状态的房间信息
    public Result leaseStatusExceptionHandler(LeaseStatusException e){
        e.printStackTrace();
        int code = e.getCode();
        String message = e.getMessage();
        return Result.build(message, code);
    }

    @ExceptionHandler(LeaseException.class)//检查公寓是否有对应的房间
    public Result leaseExceptionHandler(LeaseException e){
        e.printStackTrace();
        ResultCodeEnum resultCodeEnum = e.getResultCodeEnum();
        return  Result.build(null,resultCodeEnum);
    }

//以后有错就会返回201，而非500的错误码
    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e){
        e.printStackTrace(); //输出错误信息
        Result<Object> fail = Result.fail();
        return fail;
    }
}
